package com.tg.app.helper;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.constant.CommonConstants;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tg.app.BuildConfig;
import com.tg.app.R;
import com.tg.app.activity.base.JsCallFunName;
import com.tg.app.activity.base.WebBaseActivity;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.appcommon.android.LanguageUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.loginex.helper.LoginHelper;


import java.util.HashMap;
import java.util.Map;

public class WebViewHelper {
    private static final String TAG = "WebViewHelper";
    private WebView mWebview;
    private TextView tvTitle;
    private String mWebUrl;
    private final String alipayUrl = "alipays://platformapi/startApp?";
    private boolean isPayRedirectUrl = false;
    private ValueCallback mValueCallback;
    private final String weipayUrl = "weixin://";
    private boolean isUninstallWechat = false;//没有安装微信
    private static final int FILE_CHOOSER_RESULT_CODE =10;
    private final String wepaySign = "https://payapp.weixin.qq.com/papay";
    private boolean isWepaySign = false;
    private String redirecUrl = "";
    public static final String KEY_WEBTITLE = "key_title";
    public static final String KEY_WEBURL = "key_weburl";
    private Activity mActivity;


    public WebViewHelper(){

    }

    public void setContext(Activity activity){
        this.mActivity = activity;
    }

    public void setWebView(WebView webView){
        this.mWebview = webView;
    }

    public void setWebUrl(String url){
        this.mWebUrl = url;
    }

    public void setTvTitle(TextView tvTitle){
        this.tvTitle = tvTitle;
    }

    private void getFile(ValueCallback valueCallback){
        mValueCallback = valueCallback;
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("video/mp4,image/*");
        mActivity.startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
    }

    public void initWeb() {
        if (StringUtils.isEmpty(mWebUrl)){
            return;
        }
        WebSettings webSettings = mWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);
        // 设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // webSettings.setDatabaseEnabled(true);
        // 使用localStorage则必须打开
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        mWebview.setLayerType(View.LAYER_TYPE_HARDWARE,null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebview, true);
        }
        mWebview.setWebChromeClient(new WebChromeClient(){
            // 3.0 + 调用这个方法
            public void openFileChooser(ValueCallback filePathCallback, String acceptType) {
                getFile(filePathCallback);
            }

            // Android > 4.1.1 调用这个方法
            public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
                getFile(filePathCallback);
            }

            // Android > 5.0 调用这个方法
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                getFile(filePathCallback);
                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                TGLog.d("onReceivedTitle : title = " + title);
                if (!StringUtils.isEmpty(title) && tvTitle != null){
                    tvTitle.setText(title);
                }
            }
        });
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                TGLog.i(TAG,"url  :%s", url);
                String payRedirect = "service/pay_redirect";
                clearHistory(url);
                if (url.contains(payRedirect)) {
                    isPayRedirectUrl = true;
                    TGLog.i(TAG,"isPayRedirectUrl 1");
                }
                if (url.toLowerCase().contains(alipayUrl.toLowerCase()) || url.toLowerCase().contains(weipayUrl.toLowerCase())) {
                    if (url.toLowerCase().contains(alipayUrl.toLowerCase()) && AppUtil.checkAliPayInstalled(TGApplicationBase.getApplicationContext())) {
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                    if (url.toLowerCase().contains(weipayUrl.toLowerCase()) && !AppUtil.checkWeiXinInstalled(TGApplicationBase.getApplicationContext())) {
                        TGToast.showToast(R.string.uninstall_wechat);
                        isUninstallWechat = true;
                        view.goBack();
                        return false;
                    }
                    payAction(url);
                    view.goBack();
                    return false;
                } else if (url.toLowerCase().contains(wepaySign.toLowerCase())) {
                    Map<String, String> webviewHead = new HashMap<>();
                    webviewHead.put("Referer", "http://tange365.com");
                    Uri uri = Uri.parse(url);
                    redirecUrl = uri.getQueryParameter("redirect_url");
                    mWebview.loadUrl(url, webviewHead);
                    return false;
                } else if (StringUtils.isDownloadUrl(url)){ //如果是下载apk，跳到浏览器下载
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    if (mActivity != null){
                        mActivity.startActivity(intent);
                    }

                    return false;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (!isUninstallWechat) {
                    super.onPageFinished(view, url);
                    if (url.toLowerCase().contains(wepaySign.toLowerCase())) {
                        if (isWepaySign) {
                            getOpenLink();
                        }
                        isWepaySign = true;
                    } else {
                        isWepaySign = false;
                    }
                }

                if (isUninstallWechat ) {
                    view.clearHistory();
                }
                clearHistory(url);
                TGLog.i(TAG,"onPageFinished url  :%s， title = %s", url, view.getTitle());
                String title = view.getTitle();
                if (tvTitle!=null && !TextUtils.isEmpty(title)) {
                    tvTitle.setText(title);
                }
            }
        });

        String token = PreferenceUtil.getString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_TOKEN);
        TGLog.i(TAG,"web token :"+token);
        mWebview.addJavascriptInterface(new WebService(mActivity), "android");
        HttpConfigurations.getInstance().setLanguage(LanguageUtils.getLanguage(null));
        Uri.Builder builder = HttpConfigurations.getInstance().builderWithQueryParameter(mWebUrl,token);

        mWebUrl =  builder.toString();
        mWebUrl =  uriBuilderToString(builder);

        // 把所有的 // , 替换为 /
        mWebUrl = mWebUrl.replace("//", "/");
        // 然后把替换掉的http前缀头双斜杠补回来
        mWebUrl = mWebUrl.replace("https:/", "https://");
        mWebUrl = mWebUrl.replace("http:/", "http://");

        mWebview.loadUrl(mWebUrl);
    }

    protected String uriBuilderToString(Uri.Builder builder){
        Uri url = builder.build();
        String urlString = url.toString();
        if (!TextUtils.isEmpty(url.getEncodedFragment())){
            String fragment = "#"+url.getEncodedFragment();
            urlString = urlString.replace(fragment,"");
            if (fragment.contains("?")){
                fragment = fragment.concat("&");
            }else {
                fragment = fragment.concat("?");
            }
            urlString = urlString.replace("?",fragment);
        }
        return  urlString;
    }

    private void payAction(String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (mActivity != null){
            mActivity.startActivityForResult(intent, 100);
        }
    }

    private void getOpenLink() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebview.evaluateJavascript("javascript:(function() { return server.content; })();", s -> {
                TGLog.i(TAG,"evaluateJavascript:" + s);
                WebBaseActivity.SignPay signPay = JSON.parseObject(s, WebBaseActivity.SignPay.class);
                if (signPay!=null&&signPay.errcode == 0) {
                    if (!TextUtils.isEmpty(signPay.openlink)){
                        if (signPay.openlink.contains(alipayUrl)){
                            if (AppUtil.checkAliPayInstalled(TGApplicationBase.getApplicationContext())){
                                TGToast.showToast(R.string.uninstall_alipay);
                            }else {
                                payAction(signPay.openlink);
                            }
                        }
                        if (signPay.openlink.contains(weipayUrl)){
                            if (!AppUtil.checkWeiXinInstalled(TGApplicationBase.getApplicationContext())){
                                TGToast.showToast(R.string.uninstall_wechat);
                            }else {
                                payAction(signPay.openlink);
                            }
                        }
                        mWebview.goBack();
                    }

                }
                //将button显示的文字改成JS返回的字符串
            });
        }

    }

    private void clearHistory(String url){
        String curUrl ="";
        String localUrl ="";
        int index = url.indexOf("?");
        if (index>0){
            curUrl = url.substring(0,index);
        }
        int i = mWebUrl.indexOf("?");
        if (i>0){
            localUrl = mWebUrl.substring(0,i);
        }
        if (!TextUtils.isEmpty(localUrl)&&localUrl.contains(curUrl)){
            mWebview.clearHistory();
            isPayRedirectUrl = false;
        }
    }



    private class WebService {
        Activity activity;

        public WebService(Activity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void jumpAddDevice() {
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
        @JavascriptInterface
        public void jumpDeviceList() {
            TGLog.i(TAG, "jumpDeviceList");
            if (!activity.isFinishing()) {

                Intent i= new Intent();
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                i.setClass(TGApplicationBase.getApplicationContext(), DeviceListActivity.class);
                activity.startActivity(i);
                activity.finish();
            }
        }
        @JavascriptInterface
        public String jsCallFunc(String params){
            TGLog.i(TAG, "params = " + params);
            if (StringUtils.isEmpty(params)){
                return null;
            }

            JSONObject object = JSONObject.parseObject(params);
            if (object == null){
                return null;
            }

            String func = object.getString("funcName");
            if (StringUtils.isEmpty(func)){
                return null;
            }
            String callback = object.getString("callback");
            String param = object.getString("param");
            return jsCallFuncImpl(func, callback, param);
        }

        private String jsCallFuncImpl(String func, String callback, String param){
            TGLog.i(TAG, "func" + func + ", param = " + param);
            if (StringUtils.equalsIgnoreCase(JsCallFunName.funcImplemented, func)){
                boolean isFun = JsCallFunName.isJsFun(param);
                return isFun? "1" : "0";
            }
            if (StringUtils.equalsIgnoreCase(JsCallFunName.openWebview, func)){
                TGThreadPool.executeOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(param);
                        boolean autoClosePreviousWebview = jsonObject.getBoolean("autoCloseCurrentWebview");
                        String url = jsonObject.getString("url");
                        ActivityHelper.showWebPopWindow(activity, autoClosePreviousWebview, url);
                    }
                });

            }
            else if (StringUtils.equalsIgnoreCase(JsCallFunName.setBackButton, func) || StringUtils.equalsIgnoreCase(JsCallFunName.setCloseButton, func)){
                TGThreadPool.executeOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(param);
                        boolean show = jsonObject.getBoolean("visible");
                        if (StringUtils.equalsIgnoreCase(JsCallFunName.setBackButton, func)){
                            ActivityHelper.setBackButton(activity, show);
                        }else{
                            ActivityHelper.setCloseButton(activity, show);
                        }

                    }
                });

            }
            else if (JsCallFunName.unregistration.equals(func)){
                activity.runOnUiThread(() -> {
                    if (!activity.isFinishing()){
                        activity.finish();
                        PreferenceUtil.setBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_LOGIN, false);
                        PreferenceUtil.setBoolean(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_AUTO_WECHAT_LOGIN, false);
                        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_PWD, "");
                        PreferenceUtil.setString(TGApplicationBase.getApplicationContext(), CommonConstants.PRE_USER_NAME, "");
                        TGLog.d(TGLog.TAG, "jsCallFuncImpl");

                        ActivityHelper.startLoginActivity(activity, LoginHelper.TYPE_LOGOUT);
                    }
                });
            }else if (JsCallFunName.setTitle.equalsIgnoreCase(func)){


            } else if (JsCallFunName.shareText.equals(func)){ // 分享纯文本
                activity.runOnUiThread(() -> {
                    JSONObject shareJson = null;
                    try {
                        shareJson = JSONObject.parseObject(param);
                    } catch (Throwable exJson) {
                        return;
                    }

                    if (shareJson == null){
                        return;
                    }

                    final String shareTitle = shareJson.containsKey("title") ? shareJson.getString("title") : "";
                    final String shareText = shareJson.containsKey("text") ? shareJson.getString("text") : "";

                    if (!TextUtils.isEmpty(shareText)) {
                        final Intent sendIntent = new Intent();
                        sendIntent.setAction(Intent.ACTION_SEND);
                        if (!TextUtils.isEmpty(shareTitle)) {
                            sendIntent.putExtra(Intent.EXTRA_TITLE, shareTitle);
                        }
                        sendIntent.putExtra(Intent.EXTRA_TEXT, shareText);
                        sendIntent.setType("text/plain");
                        Intent shareIntent = Intent.createChooser(sendIntent, null);
                        activity.startActivity(shareIntent);
                    }
                });
            } else if (JsCallFunName.closeWebview.equalsIgnoreCase(func)){
                TGLog.d(TAG,"closeWebview");
                activity.runOnUiThread(() -> {
                    if (!activity.isFinishing()){
                        TGLog.d(TAG,"setResult");
                        activity.setResult(1);
                        activity.finish();
                    }

                });

            }
            return  null;
        }
    }
}
